package ace.module.product.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.model.SaveContext;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.utils.SaveContextUtils;
import ace.cmp.util.AceAssertUtils;
import ace.cmp.util.AceEnumUtils;
import ace.cmp.util.AceNumberUtils;
import ace.module.common.core.impl.manager.impl.AbstractEntityOfAppManager;
import ace.module.product.api.enums.PmsProductAuditStatusEnum;
import ace.module.product.api.enums.PmsProductSaleStatusEnum;
import ace.module.product.api.model.dto.PmsProductDto;
import ace.module.product.api.model.input.PmsProductBaseSaveInput;
import ace.module.product.core.impl.dao.entity.PmsApplication;
import ace.module.product.core.impl.dao.entity.PmsProduct;
import ace.module.product.core.impl.dao.repository.PmsProductRepository;
import ace.module.product.core.impl.manager.PmsProductManager;
import ace.module.product.core.impl.manager.generator.ProductSnGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

/**
 * 商品基础资料 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class PmsProductManagerImpl
    extends AbstractEntityOfAppManager<PmsProduct, Long, PmsProductDto>
    implements PmsProductManager {

  private final PmsProductRepository pmsProductRepository;


  @Override
  public SaveContext<PmsProduct> assembleSaveContext(PmsApplication pmsApplication, PmsProductBaseSaveInput pmsProductBaseSaveInput) {

    AceEnumUtils.getEnum(PmsProductAuditStatusEnum.class, pmsProductBaseSaveInput.getAuditStatus());
    AceEnumUtils.getEnum(PmsProductSaleStatusEnum.class, pmsProductBaseSaveInput.getSaleStatus());
    boolean isAdd = AceNumberUtils.isNullOrZero(pmsProductBaseSaveInput.getId());
    PmsProduct product;
    if (isAdd) {
      product = PmsProduct.builder()
          .id(this.getNewId())
          .pmsAppId(pmsApplication.getId())

          .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
          .createTime(System.currentTimeMillis())
          .updateTime(System.currentTimeMillis())
          .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
          .build();
    } else {
      product = pmsProductRepository.getById(pmsProductBaseSaveInput.getId());
      AceAssertUtils.isNull(product, String.format("[%s]的商品不存在", pmsProductBaseSaveInput.getId()));
    }
    BeanUtils.copyProperties(pmsProductBaseSaveInput, product);
    if (StringUtils.isEmpty(product.getSn())) {
      product.setSn(product.getId().toString());
    }
    return SaveContextUtils.of(product, isAdd);
  }
}
